'use strict';

angular.module('myApp.students_add', [])

.controller('students_addCtrl', ['$scope','$routeParams','$http','$location',
    function($scope,$routeParams,$http,$location){
        //加载班级信息
        $http.get('v1/classes').success(function(data){
            $scope.values = [];
            var data = data.resule.data;
            for (var i = 0; i < data.length; i++) {
                $scope.values.push({'id':data[i].id,"name":data[i].grade+data[i].class});
            };
            $scope.selectParents = [
                {id : 1,name : '爸爸'},
                {id : 2,name : '妈妈'},
                {id : 3,name : '爷爷'},
                {id : 4,name : '奶奶'},
                {id : 5,name : '其他'}
            ];

            //初始化信息：判断是编辑还是新建学生
            if($routeParams.id){
                $http.get('v1/student/'+$routeParams.id).success(function(data){
                    $scope.student = {"classes_id":data.result[0].id,"relation":data.result[0].relation}; 
                    $scope.student = data.result[0];
                    $scope.student.parent_name = data.result[0].parents_name;
                    $scope.student.nativeid = data.result[0].parents_nativeid;
                    $scope.student.tel = data.result[0].parents_tel;
                });
                //点击提交后的动作
                $scope.submit = function(){
                    $http.put('v1/student/'+$routeParams.id,$scope.student).success(function(data){
                        if( !data.error ){
                            alert(data.message);
                            window.location.href = '#/students';
                        }else{
                            alert(data.message);
                        }
                    });
                }; 

            }else{
                $scope.student = {"classes_id":$scope.values[0].id,"relation":$scope.selectParents[0].id};
                //点击提交按钮后的动作
                $scope.submit = function(){
                    console.log(123);
                    $http.post('v1/student',$scope.student).success(function(data){
                        if( !data.error ){
                            alert("新增成功","success");
                            window.location.href = '#/students';
                        }else{
                            alert(data.message);
                        }
                    });
                };

            };
        });  
}]);

